package com.fancy.learncenter.activity;

import android.app.Dialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSnapHelper;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.fancy.learncenter.activity.base.BaseActivity;
import com.fancy.learncenter.adapter.PicDetailAdapter;
import com.fancy.learncenter.adapter.YgtPicGallerAdapter;
import com.fancy.learncenter.bean.BaseDataBean;
import com.fancy.learncenter.bean.PicSavaDataBean;
import com.fancy.learncenter.bean.YgtGallaryDataBean;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.net.IdeaObserver;
import com.fancy.learncenter.utils.PermissionUtils;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;
import com.fancy.learncenter.view.CustomProgressDialog;
import com.fancy.learncenter.view.TopBanner;
import com.google.gson.Gson;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.TResult;
import com.superservice.lya.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;

public class YgtGalleryActivity extends BaseActivity {

    String classifyId;

    public static String PIC_KEY = "PIC_KEY";
    public static String PIC_POSITION_KEY = "PIC_POSITION_KEY";

    @Bind(R.id.recycleView)
    RecyclerView recycleView;

    PicDetailAdapter picDetailAdapter;
    ArrayList<String> itemDatas;
    int position = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ygt_gallery, Status.STATUS);
        ButterKnife.bind(this);

        initToolbar("图集");

        classifyId = getIntent().getStringExtra("classifyId");


        setRight("添加图集", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(YgtGalleryActivity.this, YgtEditGalleryActivity.class);

                intent.putExtra("classifyId", classifyId);

                startActivity(intent);
            }
        });
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏

//        itemDatas = getIntent().getStringArrayListExtra(PIC_KEY);
//        position = getIntent().getIntExtra(PIC_POSITION_KEY, 0);

        picDetailAdapter = new PicDetailAdapter(this, new ArrayList(), false);
        picDetailAdapter.setSavaCallBack(new PicDetailAdapter.SavaCallBack() {
            @Override
            public void saveCallBack(int position) {
                curSava = position;
                savaImg(picDetailAdapter.itemDatas.get(position).getImgUrl());
            }
        });


        linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recycleView.setLayoutManager(linearLayoutManager);

        new PagerSnapHelper().attachToRecyclerView(recycleView);

        recycleView.setAdapter(picDetailAdapter);

        Utils.MoveToPosition(linearLayoutManager, recycleView, position);

        dialog = CustomProgressDialog.creatRequestDialog(this);
    }

    LinearLayoutManager linearLayoutManager;

    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }

    Dialog dialog;
    Bitmap bitmap;

    @Override
    public void finish() {
        super.finish();
        if (bitmap != null) {
            bitmap.recycle();
        }

        if (dialog.isShowing()) {
            dialog.dismiss();
        }

    }


    public void savaImg(String str) {

        HttpMehtod.getInstance().downImg(str, new Observer<ResponseBody>() {
            @Override
            public void onSubscribe(Disposable d) {
                dialog.show();
            }

            @Override
            public void onNext(ResponseBody value) {
                dialog.dismiss();
                byte[] bys = new byte[0];
                try {
                    bys = value.bytes(); //注意：把byte[]转换为bitmap时，也是耗时操作，也必须在子线程
                    bitmap = BitmapFactory.decodeByteArray(bys, 0, bys.length);
                    runOnUiThread(new Runnable() {//开启主线程更新UI
                        @Override
                        public void run() {

                            try {//调用saveFile方法
                                saveImageToGallery(bitmap);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


            @Override
            public void onError(Throwable e) {
                dialog.dismiss();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    int curSava = 0;

    public void saveImageToGallery(Bitmap bmp) {
        // 首先保存图片
        String fileName = Utils.getPicRootPath() + System.currentTimeMillis() + ".jpg";
        File file = new File(fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();

            picDetailAdapter.itemDatas.get(curSava).setSava(true);

            picDetailAdapter.notifyDataSetChanged();

            ToastUtil.show("图片已保存至 /LinYa文件下");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    private void getData() {

        Map maps = new HashMap();

        maps.put("classifyId", classifyId);

        HttpMehtod.getInstance().ygtGallery(maps, new IdeaObserver<BaseDataBean<List<YgtGallaryDataBean>>>(this, true) {

            @Override
            public void onSuccess(BaseDataBean<List<YgtGallaryDataBean>> listBaseDataBean) {

                if (listBaseDataBean.getData() != null && listBaseDataBean.getData().size() > 0) {
//                    viewPager.setResData(listBaseDataBean.getData(), R.layout.banner_item);
                    ArrayList<String> itemDatas = new ArrayList<>();
                    for (int i = 0; i < listBaseDataBean.getData().size(); i++) {
                        itemDatas.add(listBaseDataBean.getData().get(i).getImgsrc());
                    }


                    ArrayList<PicSavaDataBean> datas = new ArrayList<>();
                    for (int i = 0; i < itemDatas.size(); i++) {
                        PicSavaDataBean picSavaDataBean = new PicSavaDataBean();

                        picSavaDataBean.setImgUrl(itemDatas.get(i));

                        datas.add(picSavaDataBean);
                    }

                    picDetailAdapter.notifyDataSetChanged(datas);
                }

//                viewPager.setResData(listBaseDataBean.getData(), R.layout.banner_item);


            }

            @Override
            public void onFail(int errorCode) {

            }

        });

    }

}
